from magika import Magika
from pathlib import Path


class FileAnalyzer:
    """利用Magika对文件进行解析,支持的文件类型见：https://github.com/google/magika/blob/main/docs/supported_content_types_list.md"""

    @staticmethod
    def detect_file_type(file_path: str):
        """通过文件路径判断文件类型"""

        file_path = Path(file_path)
        if not file_path.exists():
            raise FileNotFoundError(f"文件不存在: {file_path}")

        magika = Magika()
        result = magika.identify_path(file_path)
        return result.output.ct_label, result.output.mime_type

    def detect_file_type_by_content(content: str):
        """通过文件内容判断文件类型"""

        magika = Magika()
        result = magika.identify_bytes(content)
        return result.output.ct_label, result.output.mime_type


if __name__ == "__main__":
    # print(FileAnalyzer.detect_file_type("D:/Downloads/WeCom_4.1.28.6019.exe"))
    print(
        FileAnalyzer.detect_file_type_by_content(
            b"# Example\nThis is an example of markdown!"
        )
    )
